package com.jxl.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jxl.common.constant.PasswordConstant;
import com.jxl.common.constant.StatusConstant;
import com.jxl.common.result.PageResult;
import com.jxl.mapper.AdminMapper;
import com.jxl.pojo.dto.AdminDTO;
import com.jxl.pojo.dto.AdminPageQueryDTO;
import com.jxl.pojo.entity.Admin;
import com.jxl.service.AdminService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;
    /**
     * 根据id查询管理员信息
     * @param id
     * @return
     */
    @Override
    public Admin getAdminById(Long id) {
        Admin admin =adminMapper.getAdminById(id);
        admin.setPasswordHash("*****");
        return admin;
    }

    /**
     * 分页查询管理员信息
     * @param adminPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(AdminPageQueryDTO adminPageQueryDTO) {
        PageHelper.startPage(adminPageQueryDTO.getPage(), adminPageQueryDTO.getPageSize());
        Page<Admin> page = adminMapper.pageQuery(adminPageQueryDTO);
        long total = page.getTotal();
        List<Admin> records = page.getResult();
        return new PageResult(total, records);
    }

    /**
     * 新增管理员信息
     * @param adminDTO
     */
    @Override
    public void save(AdminDTO adminDTO) {
        Admin admin = new Admin();
        BeanUtils.copyProperties(adminDTO, admin);
        admin.setIsEnabled(StatusConstant.ENABLE);
        admin.setPasswordHash(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        admin.setRegistrationDate(LocalDateTime.now());
        admin.setAccountUpdatedAt(LocalDateTime.now());
        adminMapper.insert(admin);

    }

    /**
     * 修改管理员信息
     * @param adminDTO
     */
    @Override
    public void update(AdminDTO adminDTO) {
        Admin admin = new Admin();
        BeanUtils.copyProperties(adminDTO, admin);
        admin.setAccountUpdatedAt(LocalDateTime.now());
        adminMapper.update(admin);
    }

    /**
     * 启用或禁用管理员
     * @param status
     * @param id
     */
    @Override
    public void setStatus(Integer status, Long id) {
        Admin admin = new Admin();
        admin.setAdminId(id);
        admin.setIsEnabled(status);
        adminMapper.update(admin);
    }
}
